package com.yunji.cabinet.device;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

/**
 * @author : peter-zhu
 * @date : 2025/5/15 18:27
 * @description : TODO
 **/
@Slf4j
public class DeviceSignatureUtil {
    private static final String SECRET = "hmac-secret-coffee-device";
    public static final String HMAC_SHA256 = "HmacSHA256";

    public static String generateSignature(Long timestamp, String nonce, String body, String secret) {
        if (body == null)
            body = "";
        String contentToSign = timestamp   + nonce   + body;
//        log.debug("DeviceSignatureUtil generateSignature sign:{}",contentToSign);
//        log.debug("DeviceSignatureUtil generateSignature nonce:{}",nonce);
//        log.debug("DeviceSignatureUtil generateSignature body:{}",body);
        try {
            Mac mac = Mac.getInstance(HMAC_SHA256);
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256));
            byte[] hash = mac.doFinal(contentToSign.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (Exception e) {
            log.error("DeviceSignatureUtil generateSignature error,data:{}", body, e);
        }
        return null;
    }

    private static void addSignHeader(HttpRequest request, String json) {
        long timestamp = System.currentTimeMillis() / 1000;
        String nonce = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        String signature = generateSignature(timestamp, nonce, json, SECRET);
        Map<String, String> headers = Maps.newHashMap();
        headers.put("X-Device-Timestamp", String.valueOf(timestamp));
        headers.put("X-Device-Nonce", nonce);
        headers.put("X-Device-Signature", signature);
        request.addHeaders(headers);
    }

    public static String post(String url, String json) {
        HttpRequest post = HttpUtil.createPost(url);
        addSignHeader(post, json);
        try (HttpResponse execute = post.body(json).execute()) {
            return execute.body();
        }
    }

    public static String get(String url) {
        HttpRequest get = HttpUtil.createGet(url);
        addSignHeader(get, null);
        try (HttpResponse execute = get.execute()) {
            return execute.body();
        }
    }


}
